package com.example.administrator.liveapp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.bean.JsonBean;
import com.example.administrator.liveapp.bean.MessageRemindBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.CheckInfoUtill;
import com.example.administrator.liveapp.utils.GetJsonDataUtil;
import com.google.gson.Gson;
import com.suke.widget.SwitchButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 添加商城收货地址activity
 */

public class FillAddress extends AppCompatActivity implements View.OnClickListener {

    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread threads;
    private boolean isLoaded = false;
    private TextView text_home;//显示省市区(所在地)
    private RelativeLayout btn_shows;

    private EditText ed_consignee, ed_contact_phone, all_address;//收货人、联系电话、详细地址
    private TextView add_newName;
    private String token;
    private String addressId;//地址id
    private com.suke.widget.SwitchButton switch_button;

    public FillAddress() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fill_address);
        ApplicationUtils applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        initView();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (threads == null) {//如果已创建就不再重新创建子线程了
                        threads = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        threads.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;

            }
        }
    };

    private void initView() {
        switch_button = (com.suke.widget.SwitchButton) findViewById(R.id.switch_button);
        text_home = (TextView) findViewById(R.id.text_home);
        ed_consignee = (EditText) findViewById(R.id.ed_consignee);
        ed_contact_phone = (EditText) findViewById(R.id.ed_contact_phone);
        all_address = (EditText) findViewById(R.id.all_address);
        add_newName = (TextView) findViewById(R.id.add_newName);
        btn_shows = (RelativeLayout) findViewById(R.id.btn_shows);
        findViewById(R.id.add_returns).setOnClickListener(this);
        findViewById(R.id.new_addition).setOnClickListener(this);
        btn_shows.setOnClickListener(this);
        Intent intent = getIntent();
        token = intent.getStringExtra("token");
        if (token.equals("1")) {
            add_newName.setText("编辑地址");
            ed_consignee.setText(intent.getStringExtra("nickName"));
            ed_contact_phone.setText(intent.getStringExtra("telNumber"));
            all_address.setText(intent.getStringExtra("detailAddress"));
            text_home.setText(intent.getStringExtra("orderAddress"));
            addressId = intent.getStringExtra("addressId");
            if (intent.getStringExtra("addStatus").equals("1")) {
                switch_button.setChecked(true);
            } else {
                switch_button.setChecked(false);
            }
        } else if (token.equals("2")) {
            add_newName.setText("新增地址");
        } else if (token.equals("3")) {
            add_newName.setText("新增地址");
        }else if(token.equals("4")){
            add_newName.setText("编辑地址");
            ed_consignee.setText(intent.getStringExtra("nickName"));
            ed_contact_phone.setText(intent.getStringExtra("telNumber"));
            all_address.setText(intent.getStringExtra("detailAddress"));
            text_home.setText(intent.getStringExtra("orderAddress"));
            addressId = intent.getStringExtra("addressId");
            if (intent.getStringExtra("addStatus").equals("1")) {
                switch_button.setChecked(true);
            } else {
                switch_button.setChecked(false);
            }
        }
        initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btn_shows:
                if (isLoaded) {
                    ShowPickerView();
                }
                break;
            case R.id.add_returns:
                finish();
                break;
            case R.id.new_addition:
                if (token.equals("1")) {//修改地址
                    if (CheckInfoUtill.isMobileNO(ed_contact_phone.getText().toString())) {
                        String url = AppUrl.URL + AppUrl.editAddress;
                        Map<String, String> map = new HashMap<>();
                        map.put("addressId", addressId);
                        map.put("nickName", ed_consignee.getText().toString());//收货人
                        map.put("telNumber", ed_contact_phone.getText().toString());//手机号
                        map.put("orderAddress", text_home.getText().toString());//地址
                        map.put("detailAddress", all_address.getText().toString());//详细地址
                        if (switch_button.isChecked() == false) {
                            map.put("addStatus", "0");//是否地址默认
                        } else {
                            map.put("addStatus", "1");//是否地址默认
                        }
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String code = jsonObject.optString("code");
                                if (code.equals("47010")) {
                                    Toast.makeText(FillAddress.this, "修改收货地址成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(FillAddress.this, "修改收货地址失败" + code, Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(FillAddress.this, "修改收货地址错误" + ex.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFinished() {
                                super.onFinished();
                                Intent intent = new Intent(FillAddress.this, ReceivingAddressPage.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                                finish();
                            }
                        });
                    } else {
                        Toast.makeText(this, "请填写正确联系方式", Toast.LENGTH_SHORT).show();
                    }
                } else if (token.equals("2")) {//新增地址
                    if (CheckInfoUtill.isMobileNO(ed_contact_phone.getText().toString())) {
                        String url = AppUrl.URL + AppUrl.addAddress;
                        Map<String, String> map = new HashMap<>();
                        map.put("addressUid", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        map.put("nickName", ed_consignee.getText().toString());//收货人
                        map.put("telNumber", ed_contact_phone.getText().toString());//手机号
                        map.put("orderAddress", text_home.getText().toString());//地址
                        map.put("detailAddress", all_address.getText().toString());//详细地址
                        if (switch_button.isChecked() == false) {
                            map.put("addStatus", "0");//是否地址默认
                        } else {
                            map.put("addStatus", "1");//是否地址默认
                        }
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String code = jsonObject.optString("code");
                                if (code.equals("47000")) {
                                    Toast.makeText(FillAddress.this, "添加收货地址成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(FillAddress.this, "添加收货地址失败" + code, Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(FillAddress.this, "添加收货地址错误" + ex.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFinished() {
                                super.onFinished();
                                Intent intent = new Intent(FillAddress.this, ReceivingAddressPage.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                                finish();
                            }
                        });

                    }else {
                        Toast.makeText(this, "请填写正确联系方式", Toast.LENGTH_SHORT).show();
                    }
                } else if (token.equals("3")) {//新增地址(订单页面的新增)
                    if (CheckInfoUtill.isMobileNO(ed_contact_phone.getText().toString())) {
                        String url = AppUrl.URL + AppUrl.addAddress;
                        Map<String, String> map = new HashMap<>();
                        map.put("addressUid", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        map.put("nickName", ed_consignee.getText().toString());//收货人
                        map.put("telNumber", ed_contact_phone.getText().toString());//手机号
                        map.put("orderAddress", text_home.getText().toString());//地址
                        map.put("detailAddress", all_address.getText().toString());//详细地址
                        if (switch_button.isChecked() == false) {
                            map.put("addStatus", "0");//是否地址默认
                        } else {
                            map.put("addStatus", "1");//是否地址默认
                        }
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String code = jsonObject.optString("code");
                                if (code.equals("47000")) {
                                    Toast.makeText(FillAddress.this, "添加收货地址成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(FillAddress.this, "添加收货地址失败" + code, Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(FillAddress.this, "添加收货地址错误" + ex.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFinished() {
                                super.onFinished();
                                Intent intent = new Intent();
                                intent.putExtra("nickName", ed_consignee.getText().toString());//收货人
                                intent.putExtra("telNumber", ed_contact_phone.getText().toString());//手机号
                                intent.putExtra("detailAddress", all_address.getText().toString());//详细地址
                                setResult(RESULT_OK, intent);
                                overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                                finish();
                            }
                        });
                    }else {
                        Toast.makeText(this, "请填写正确联系方式", Toast.LENGTH_SHORT).show();
                    }
                } else if (token.equals("4")) {//修改地址
                    if (CheckInfoUtill.isMobileNO(ed_contact_phone.getText().toString())) {
                        String url = AppUrl.URL + AppUrl.editAddress;
                        Map<String, String> map = new HashMap<>();
                        map.put("addressId", addressId);
                        map.put("nickName", ed_consignee.getText().toString());//收货人
                        map.put("telNumber", ed_contact_phone.getText().toString());//手机号
                        map.put("orderAddress", text_home.getText().toString());//地址
                        map.put("detailAddress", all_address.getText().toString());//详细地址
                        if (switch_button.isChecked() == false) {
                            map.put("addStatus", "0");//是否地址默认
                        } else {
                            map.put("addStatus", "1");//是否地址默认
                        }
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String code = jsonObject.optString("code");
                                if (code.equals("47010")) {
                                    Toast.makeText(FillAddress.this, "修改收货地址成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(FillAddress.this, "修改收货地址失败" + code, Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(FillAddress.this, "修改收货地址错误" + ex.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFinished() {
                                super.onFinished();
                                Intent intent = new Intent();
                                intent.putExtra("nickName", ed_consignee.getText().toString());//收货人
                                intent.putExtra("telNumber", ed_contact_phone.getText().toString());//手机号
                                intent.putExtra("detailAddress", all_address.getText().toString());//详细地址
                                setResult(RESULT_FIRST_USER, intent);
                                overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                                finish();
                            }
                        });
                    } else {
                        Toast.makeText(this, "请填写正确联系方式", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    private void initData() {
        switch_button.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                //TODO do your job
            }
        });
    }

    /**
     * 省市区3级选择器
     */
    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() +
                        options2Items.get(options1).get(options2) +
                        options3Items.get(options1).get(options2).get(options3);

                text_home.setText(tx);
//                Toast.makeText(PersonalInformationPage.this,tx,Toast.LENGTH_SHORT).show();
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.black))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.main))//取消按钮文字颜色.build();
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}
